package com.qf.controller;

import com.qf.entity.User;
import com.qf.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "http://localhost:8083", allowCredentials = "true") // 前端端口
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;

    // 登录接口
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User dbUser = userService.login(user.getUsername(), user.getPassword());
        if (dbUser != null) {
            session.setAttribute("user", dbUser); // 保存登录状态
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("user", dbUser);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }

    // 查询所有用户（需要登录）
    @GetMapping("/users")
    public Map<String, Object> getAllUsers(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            result.put("success", false);
            result.put("message", "未登录");
            return result;
        }
        List<User> users = userService.getAllUsers();
        result.put("success", true);
        result.put("data", users);
        return result;
    }
}